package neatlogic.module.change.api;

import neatlogic.framework.auth.core.AuthAction;
import neatlogic.framework.common.constvalue.ApiParamType;
import neatlogic.framework.common.constvalue.GroupSearch;
import neatlogic.framework.crossover.CrossoverServiceFactory;
import neatlogic.framework.exception.type.ParamIrregularException;
import neatlogic.framework.process.auth.PROCESS_BASE;
import neatlogic.framework.process.crossover.IProcessStepHandlerCrossoverUtil;
import neatlogic.framework.process.dto.ProcessTaskStepVo;
import neatlogic.framework.restful.annotation.Description;
import neatlogic.framework.restful.annotation.Input;
import neatlogic.framework.restful.annotation.OperationType;
import neatlogic.framework.restful.annotation.Param;
import neatlogic.framework.restful.constvalue.OperationTypeEnum;
import neatlogic.framework.restful.core.privateapi.PrivateApiComponentBase;
import neatlogic.framework.change.constvalue.ChangeAuditDetailType;
import neatlogic.framework.change.constvalue.ChangeAuditType;
import neatlogic.framework.change.constvalue.ChangeOperationType;
import neatlogic.module.change.dao.mapper.ChangeMapper;
import neatlogic.framework.change.dto.ChangeStepTeamVo;
import neatlogic.framework.change.dto.ChangeStepUserVo;
import neatlogic.framework.change.dto.ChangeStepVo;
import neatlogic.framework.change.dto.ChangeVo;
import neatlogic.framework.change.exception.ChangeNoPermissionException;
import neatlogic.framework.change.exception.ChangeNotFoundException;
import neatlogic.module.change.service.ChangeService;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
@AuthAction(action = PROCESS_BASE.class)
@OperationType(type = OperationTypeEnum.OPERATE)
public class ChangeStepWorkerBatchUpdateApi extends PrivateApiComponentBase {

    @Autowired
    private ChangeMapper changeMapper;

    @Autowired
    private ChangeService changeService;

    @Override
    public String getToken() {
        return "change/step/worker/batchupdate";
    }

    @Override
    public String getName() {
        return "nmca.changestepworkerbatchupdateapi.getname";
    }

    @Override
    public String getConfig() {
        return null;
    }

    @Input({
            @Param(name = "processTaskStepId", type = ApiParamType.LONG, desc = "term.itsm.processtaskstepid"),
            @Param(name = "changeId", type = ApiParamType.LONG, isRequired = true, desc = "term.change.changeid"),
            @Param(name = "worker", type = ApiParamType.STRING, isRequired = true, minLength = 37, maxLength = 37, desc = "term.itsm.worker"),
            @Param(name = "source", type = ApiParamType.STRING, desc = "common.source")
    })
    @Description(desc = "nmca.changestepworkerbatchupdateapi.getname")
    @Override
    public Object myDoService(JSONObject jsonObj) throws Exception {
        Long changeId = jsonObj.getLong("changeId");
        ChangeVo changeVo = changeMapper.getChangeById(changeId);
        if (changeVo == null) {
            throw new ChangeNotFoundException(changeId);
        }
        /** 获取当前变更锁 **/
        changeMapper.getChangeLockById(changeId);
        String owner = changeMapper.getChangeUserByChangeId(changeId);
        if (StringUtils.isNotBlank(owner)) {
            changeVo.setOwner(GroupSearch.USER.getValuePlugin() + owner);
        }
        if (!changeService.isBatchUpdateChangeStepWorker(changeVo)) {
            throw new ChangeNoPermissionException(ChangeOperationType.BATCHEDITCHANGESTEPWORKER.getText());
        }

        String worker = jsonObj.getString("worker");
        if (!worker.startsWith(GroupSearch.USER.getValuePlugin()) && !worker.startsWith(GroupSearch.TEAM.getValuePlugin())) {
            throw new ParamIrregularException("worker");
        }
        String[] split = worker.split("#");
        /** 更新所有变更步骤处理人或组 **/
        List<ChangeStepVo> changeStepList = changeMapper.getChangeStepListByChangeId(changeId);
        if (CollectionUtils.isNotEmpty(changeStepList)) {
            changeMapper.deleteChangeStepTeamByChangeId(changeId);
            changeMapper.deleteChangeStepUserByChangeId(changeId);
            for (ChangeStepVo changeStepVo : changeStepList) {
                if (GroupSearch.USER.getValue().equals(split[0])) {
                    changeMapper.insertChangeStepUser(new ChangeStepUserVo(changeStepVo.getChangeId(), changeStepVo.getId(), split[1]));
                } else if (GroupSearch.TEAM.getValue().equals(split[0])) {
                    changeMapper.insertChangeStepTeam(new ChangeStepTeamVo(changeStepVo.getChangeId(), changeStepVo.getId(), split[1]));
                }
            }
        }

        Long processTaskId = changeMapper.getProcessTaskIdByChangeId(changeId);
        ProcessTaskStepVo currentProcessTaskStepVo = new ProcessTaskStepVo();
        currentProcessTaskStepVo.setProcessTaskId(processTaskId);
        Long currentProcessTaskStepId = jsonObj.getLong("processTaskStepId");
        currentProcessTaskStepVo.setId(currentProcessTaskStepId);
        /** 生成活动 **/
        currentProcessTaskStepVo.getParamObj().put(ChangeAuditDetailType.WORKER.getParamName(), worker);
        currentProcessTaskStepVo.getParamObj().put("source", jsonObj.getString("source"));
        IProcessStepHandlerCrossoverUtil processStepHandlerCrossoverUtil = CrossoverServiceFactory.getApi(IProcessStepHandlerCrossoverUtil.class);
        processStepHandlerCrossoverUtil.audit(currentProcessTaskStepVo, ChangeAuditType.BATCHEDITCHANGESTEPWORKER);
        return null;
    }

}
